package me.firstapp.manage.operator;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;

import me.firstapp.common.exception.StatusHouse;
import me.firstapp.common.json.AbstractJsonObject;
import me.firstapp.common.json.PageObject;
import me.firstapp.common.json.SingleObject;
import me.firstapp.common.module.system.JsonOperator;
import me.firstapp.common.utils.ResponseUtils;
import me.firstapp.common.utils.StrUtils;
import me.firstapp.manage.common.BaseManage;
import me.firstapp.manage.utils.BizData4Page;
import me.firstapp.spi.bbs.EmailService;
import me.firstapp.spi.system.OperatorService;

@Controller
@RequestMapping(value = "/operatorManage")
public class OperatorManageAct extends BaseManage {

	@Autowired
	private OperatorService operatorService;

	@Autowired
	private EmailService emailService;

	@ResponseBody
	@RequestMapping(value = "/findOperatorPage.do", method = RequestMethod.POST)
	public void findEmailConfigPage(@RequestParam Map<String, Object> conditions, HttpServletRequest request,
			HttpServletResponse response) {

		try {
			// 搜索条件
			Map<String, Object> searchParams = new HashMap<>();
			String sSearchJson = (String) conditions.get("sSearch");
			if (StrUtils.isNotNULL(sSearchJson)) {
				JSONObject jsonObject = JSONObject.parseObject(sSearchJson);
				if (jsonObject != null) {
					Set<String> keySet = jsonObject.keySet();
					for (String key : keySet) {
						searchParams.put(key, jsonObject.get(key));
					}
				}
			}
			// 排序字段
			String mDataProp = "mDataProp_" + conditions.get("iSortCol_0");
			mDataProp = conditions.get(mDataProp).toString().replace("Str", "");
			// 排序方式
			String sSortDir_0 = (String) conditions.get("sSortDir_0");
			// 页容
			String iDisplayLengthStr = (String) conditions.get("iDisplayLength");
			// 是开始数不是当前页数...
			String iDisplayStartStr = (String) conditions.get("iDisplayStart");
			if (StrUtils.isNotNULL(iDisplayLengthStr) && StrUtils.isNotNULL(iDisplayStartStr)) {
				Integer iDisplayLength = Integer.valueOf(iDisplayLengthStr);
				Integer iDisplayStart = Integer.valueOf(iDisplayStartStr);
				// 当前页数
				Integer pageNo = iDisplayStart / iDisplayLength + 1;
				PageObject<JsonOperator> operatorPage = operatorService.findOperatorPage(pageNo, iDisplayLength,
						searchParams, mDataProp, sSortDir_0);
				SingleObject<Object> result = new SingleObject<Object>();
				BizData4Page<JsonOperator> bizData4Page = new BizData4Page<JsonOperator>();
				bizData4Page.setUserdata(conditions);
				if (operatorPage.getPage() != null) {
					bizData4Page.setPage(operatorPage.getPage().getPageNo());
					bizData4Page.setPagesize(operatorPage.getPage().getPageSize());
					bizData4Page.setRecords(operatorPage.getPage().getTotalCount());
					bizData4Page.setRows(new ArrayList<JsonOperator>(operatorPage.getPage().getList()));
					bizData4Page.setTotal(operatorPage.getPage().getTotalCount());
				}

				result.setCode(operatorPage.getCode());
				result.setMsg(operatorPage.getMsg());
				result.setObject(bizData4Page);
				ResponseUtils.renderJson(response, result);
			}
		} catch (Exception e) {
			e.printStackTrace();
			AbstractJsonObject abstractJsonObject = new AbstractJsonObject();
			abstractJsonObject.setCode("error");
			abstractJsonObject.setMsg("发生未知错误");
			ResponseUtils.renderJson(response, abstractJsonObject);
		}
	}

	@RequestMapping(value = "/addOperator.do", method = RequestMethod.POST)
	public void addOperator(String email, String password, String name, HttpServletRequest request,
			HttpServletResponse response) {
		SingleObject<JsonOperator> result = operatorService.addOperator(email, password, name);
		ResponseUtils.renderJson(response, result);
	}

	@RequestMapping(value = "/updateOperatorStatus.do", method = RequestMethod.POST)
	public void updateOperatorStatus(Long id, Integer status, HttpServletRequest request,
			HttpServletResponse response) {
		SingleObject<JsonOperator> result = operatorService.updateStatus(id, status);
		ResponseUtils.renderJson(response, result);
	}

	@RequestMapping(value = "/alterPassword.do", method = RequestMethod.POST)
	public void alterPassword(Long id, String oldPassword, String newPassword, String code, HttpServletRequest request,
			HttpServletResponse response) {
		SingleObject<JsonOperator> result = operatorService.alterPassword(id, oldPassword, newPassword, code);
		if (StatusHouse.COMMON_STATUS_OK.getCode().equals(result.getCode())) {
			String loginToken = (String) request.getSession().getAttribute("loginToken");
			request.getSession().removeAttribute("loginToken");
			request.getSession().removeAttribute("login_operator_" + loginToken);
		}
		ResponseUtils.renderJson(response, result);
	}

	@RequestMapping(value = "/sendEmailCode.do", method = RequestMethod.POST)
	public void sendEmailCode(Long operatorId, String name, String email, HttpServletRequest request,
			HttpServletResponse response) {
		SingleObject<Object> result = new SingleObject<>();
		if (StrUtils.isNULL(email)) {
			SingleObject<JsonOperator> resultOperator = null;
			if (operatorId != null) {
				resultOperator = operatorService.findOperatorById(operatorId);
			} else if (StrUtils.isNotNULL(name)) {
				resultOperator = operatorService.findOperatorByName(name);
			} else {
				result.setCode("error");
				result.setMsg("参数不正确！");
			}
			if (resultOperator != null) {
				if (StatusHouse.COMMON_STATUS_OK.getCode().equals(resultOperator.getCode())) {
					result = emailService.sendEmailCode(resultOperator.getObject().getEmail());
				} else {
					result.setCode(resultOperator.getCode());
					result.setMsg(resultOperator.getMsg());
				}
			}
		} else {
			result = emailService.sendEmailCode(email);
		}
		ResponseUtils.renderJson(response, result);
	}
}
